<template>
  <div class="consumption-profile">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h2>消费画像分析</h2>
        <p>深入分析用户消费能力、偏好和行为模式</p>
      </div>
      <div class="header-actions">
        <el-select v-model="timeRange" size="small" style="width: 120px">
          <el-option label="最近7天" value="7d" />
          <el-option label="最近30天" value="30d" />
          <el-option label="最近90天" value="90d" />
        </el-select>
        <el-button :icon="Refresh" @click="refreshData" :loading="loading">刷新</el-button>
        <el-button type="primary" :icon="Download" @click="exportReport">导出报告</el-button>
      </div>
    </div>

    <!-- 消费指标概览 -->
    <div class="consumption-metrics" v-loading="loading">
      <el-row :gutter="20">
        <el-col :xs="12" :sm="6" v-for="metric in consumptionMetrics" :key="metric.key">
          <el-card class="metric-card" :class="metric.key">
            <div class="metric-content">
              <div class="metric-icon">
                <el-icon :size="28" :color="metric.color">
                  <component :is="metric.icon" />
                </el-icon>
              </div>
              <div class="metric-info">
                <h3>{{ metric.title }}</h3>
                <p class="metric-value">{{ metric.value }}</p>
                <span class="metric-change" :class="metric.trend">
                  <el-icon :size="12">
                    <component :is="metric.trend === 'up' ? 'ArrowUp' : 'ArrowDown'" />
                  </el-icon>
                  {{ metric.change }}
                </span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 消费分析图表 -->
    <div class="consumption-charts">
      <el-row :gutter="20">
        <!-- 消费金额分布 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <h3>消费金额分布</h3>
                <el-button-group size="small">
                  <el-button :type="amountChartType === 'bar' ? 'primary' : ''" @click="amountChartType = 'bar'">
                    柱状图
                  </el-button>
                  <el-button :type="amountChartType === 'pie' ? 'primary' : ''" @click="amountChartType = 'pie'">
                    饼图
                  </el-button>
                </el-button-group>
              </div>
            </template>
            <div class="chart-container">
              <BaseChart
                v-if="amountChartType === 'bar'"
                :option="amountDistributionOption"
                height="300px"
                @chart-click="handleAmountChartClick"
              />
              <PieChartComponent
                v-else
                :data="amountDistributionData"
                height="300px"
                :radius="['40%', '70%']"
                @chart-click="handleAmountChartClick"
              />
            </div>
          </el-card>
        </el-col>

        <!-- 消费频次分析 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <h3>消费频次分析</h3>
                <span class="chart-total">平均频次: {{ avgFrequency }}次/月</span>
              </div>
            </template>
            <div class="chart-container">
              <BaseChart
                :option="frequencyDistributionOption"
                height="300px"
                @chart-click="handleFrequencyChartClick"
              />
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <!-- 商品类别偏好 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <h3>商品类别偏好</h3>
                <el-select v-model="categoryMetric" size="small" style="width: 100px">
                  <el-option label="销量" value="sales" />
                  <el-option label="金额" value="amount" />
                </el-select>
              </div>
            </template>
            <div class="chart-container">
              <BaseChart
                :option="categoryPreferenceOption"
                height="300px"
                @chart-click="handleCategoryChartClick"
              />
            </div>
          </el-card>
        </el-col>

        <!-- 消费趋势分析 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <h3>消费趋势分析</h3>
                <el-tag size="small" type="info">近30天</el-tag>
              </div>
            </template>
            <div class="chart-container">
              <BaseChart
                :option="consumptionTrendOption"
                height="300px"
                @chart-click="handleTrendChartClick"
              />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- RFM分析 -->
    <div class="rfm-analysis">
      <el-card>
        <template #header>
          <div class="chart-header">
            <h3>RFM用户价值分析</h3>
            <div class="rfm-legend">
              <span class="legend-item">
                <span class="legend-color" style="background: #67C23A;"></span>
                高价值用户
              </span>
              <span class="legend-item">
                <span class="legend-color" style="background: #E6A23C;"></span>
                中价值用户
              </span>
              <span class="legend-item">
                <span class="legend-color" style="background: #F56C6C;"></span>
                低价值用户
              </span>
            </div>
          </div>
        </template>
        <div class="rfm-content">
          <div class="rfm-grid">
            <div class="rfm-item" v-for="segment in rfmSegments" :key="segment.id">
              <div class="rfm-header">
                <h4>{{ segment.name }}</h4>
                <el-tag :type="segment.type" size="small">{{ segment.level }}</el-tag>
              </div>
              <div class="rfm-metrics">
                <div class="rfm-metric">
                  <span class="metric-label">用户数</span>
                  <span class="metric-value">{{ segment.userCount.toLocaleString() }}</span>
                </div>
                <div class="rfm-metric">
                  <span class="metric-label">占比</span>
                  <span class="metric-value">{{ segment.percentage }}%</span>
                </div>
                <div class="rfm-metric">
                  <span class="metric-label">平均消费</span>
                  <span class="metric-value">¥{{ segment.avgAmount }}</span>
                </div>
              </div>
              <div class="rfm-description">
                {{ segment.description }}
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 消费详细分析表格 -->
    <div class="consumption-table">
      <el-card>
        <template #header>
          <div class="table-header">
            <h3>消费详细分析</h3>
            <div class="table-controls">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索用户..."
                size="small"
                style="width: 200px"
                :prefix-icon="Search"
                clearable
              />
              <el-select v-model="segmentFilter" size="small" style="width: 120px">
                <el-option label="全部用户" value="" />
                <el-option label="高价值" value="high" />
                <el-option label="中价值" value="medium" />
                <el-option label="低价值" value="low" />
              </el-select>
            </div>
          </div>
        </template>

        <el-table :data="filteredTableData" v-loading="tableLoading" stripe style="width: 100%">
          <el-table-column prop="userId" label="用户ID" min-width="100" />
          <el-table-column prop="userName" label="用户名" min-width="120" />
          <el-table-column prop="totalAmount" label="总消费金额" min-width="140">
            <template #default="{ row }">
              ¥{{ row.totalAmount.toLocaleString() }}
            </template>
          </el-table-column>
          <el-table-column prop="orderCount" label="订单数量" min-width="120" />
          <el-table-column prop="avgOrderAmount" label="平均订单金额" min-width="150">
            <template #default="{ row }">
              ¥{{ row.avgOrderAmount }}
            </template>
          </el-table-column>
          <el-table-column prop="lastOrderDate" label="最近购买" min-width="120" />
          <el-table-column prop="favoriteCategory" label="偏好类别" min-width="120" />
          <el-table-column prop="rfmSegment" label="RFM分群" min-width="140">
            <template #default="{ row }">
              <el-tag :type="getRfmTagType(row.rfmSegment)" size="small">
                {{ row.rfmSegment }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button size="small" type="primary" link @click="viewUserDetail(row)">
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50]"
            :total="totalRecords"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Refresh, Download, Search, ArrowUp, ArrowDown,
  Money, ShoppingCart, TrendCharts, User
} from '@element-plus/icons-vue'
import { BaseChart, PieChart as PieChartComponent } from '@/components/charts'
import { getConsumptionProfileAnalysis, getConsumptionTableData } from '@/api/analysis'

// 响应式数据
const loading = ref(false)
const timeRange = ref('30d')
const amountChartType = ref('bar')
const categoryMetric = ref('sales')
const searchKeyword = ref('')
const segmentFilter = ref('')
const tableLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const totalRecords = ref(0)
const avgFrequency = ref(3.2)

// API数据存储
const apiData = ref({
  spending_distribution: [],
  frequency_distribution: [],
  category_preference: [],
  order_value_distribution: [],
  consumption_trend: { dates: [], amount: [], orders: [] },
  rfm_segments: [],
  summary: {
    total_revenue: 0,
    avg_order_value: 0,
    paying_users: 0,
    repeat_purchase_rate: 0,
    avg_frequency: 0
  }
})

// 消费指标数据（基于API数据计算）
const consumptionMetrics = computed(() => {
  const summary = apiData.value.summary

  return [
    {
      key: 'total_revenue',
      title: '总消费金额',
      value: summary.total_revenue ?
        `¥${(summary.total_revenue / 1000000).toFixed(1)}M` :
        '¥12.8M', // 后备数据
      change: '+18.5%',
      trend: 'up',
      icon: 'Money',
      color: '#409EFF'
    },
    {
      key: 'avg_order_value',
      title: '平均订单金额',
      value: summary.avg_order_value ?
        `¥${summary.avg_order_value.toFixed(0)}` :
        '¥286', // 后备数据
      change: '+5.2%',
      trend: 'up',
      icon: 'ShoppingCart',
      color: '#67C23A'
    },
    {
      key: 'paying_users',
      title: '付费用户数',
      value: summary.paying_users ?
        summary.paying_users.toLocaleString() :
        '45,678', // 后备数据
      change: '+12.3%',
      trend: 'up',
      icon: 'User',
      color: '#E6A23C'
    },
    {
      key: 'repeat_rate',
      title: '复购率',
      value: summary.repeat_purchase_rate ?
        `${summary.repeat_purchase_rate}%` :
        '68.5%', // 后备数据
      change: '+3.8%',
      trend: 'up',
      icon: 'TrendCharts',
      color: '#F56C6C'
    }
  ]
})

// 消费金额分布数据（基于API数据）
const amountDistributionData = computed(() => {
  if (apiData.value.spending_distribution.length > 0) {
    return apiData.value.spending_distribution.map(item => ({
      name: item.label,
      value: item.value
    }))
  }
  // 后备数据
  return [
    { name: '0-100元', value: 15680 },
    { name: '100-500元', value: 28900 },
    { name: '500-1000元', value: 18650 },
    { name: '1000-2000元', value: 12400 },
    { name: '2000-5000元', value: 8200 },
    { name: '5000元以上', value: 3170 }
  ]
})

// 消费频次分布数据（基于API数据）
const frequencyDistributionData = computed(() => {
  if (apiData.value.frequency_distribution.length > 0) {
    return apiData.value.frequency_distribution.map(item => ({
      name: item.label,
      value: item.value
    }))
  }
  // 后备数据
  return [
    { name: '1次', value: 18900 },
    { name: '2-3次', value: 25600 },
    { name: '4-6次', value: 19800 },
    { name: '7-10次', value: 12500 },
    { name: '11-20次', value: 8200 },
    { name: '20次以上', value: 3000 }
  ]
})

// 商品类别偏好数据（基于API数据）
const categoryPreferenceData = computed(() => {
  if (apiData.value.category_preference.length > 0) {
    return {
      sales: apiData.value.category_preference.map(item => ({
        name: item.label,
        value: item.sales || item.user_count || 0
      })),
      amount: apiData.value.category_preference.map(item => ({
        name: item.label,
        value: item.value || 0
      }))
    }
  }
  // 后备数据
  return {
    sales: [
      { name: '电子产品', value: 45680 },
      { name: '服装鞋帽', value: 38200 },
      { name: '家居用品', value: 28900 },
      { name: '图书音像', value: 18650 },
      { name: '运动户外', value: 15200 },
      { name: '美妆护肤', value: 12800 }
    ],
    amount: [
      { name: '电子产品', value: 8560000 },
      { name: '家居用品', value: 3280000 },
      { name: '服装鞋帽', value: 2890000 },
      { name: '运动户外', value: 1650000 },
      { name: '美妆护肤', value: 1280000 },
      { name: '图书音像', value: 680000 }
    ]
  }
})

// 消费趋势数据（基于API数据）
const consumptionTrendData = computed(() => {
  if (apiData.value.consumption_trend && apiData.value.consumption_trend.dates.length > 0) {
    return apiData.value.consumption_trend
  }
  // 后备数据
  return {
    dates: ['01-01', '01-05', '01-10', '01-15', '01-20', '01-25', '01-30'],
    amount: [850000, 920000, 880000, 950000, 1020000, 980000, 1050000],
    orders: [2850, 3200, 2980, 3450, 3680, 3520, 3800]
  }
})

// RFM分析数据（基于API数据）
const rfmSegments = computed(() => {
  if (apiData.value.rfm_segments.length > 0) {
    return apiData.value.rfm_segments
  }
  // 后备数据
  return [
  {
    id: 1,
    name: '重要价值客户',
    level: '高价值',
    type: 'success',
    userCount: 8650,
    percentage: 18.9,
    avgAmount: 2850,
    description: '最近购买时间近、购买频率高、消费金额大的用户'
  },
  {
    id: 2,
    name: '重要保持客户',
    level: '高价值',
    type: 'success',
    userCount: 6200,
    percentage: 13.6,
    avgAmount: 2150,
    description: '购买频率高、消费金额大，但最近购买时间较远'
  },
  {
    id: 3,
    name: '重要发展客户',
    level: '中价值',
    type: 'warning',
    userCount: 12800,
    percentage: 28.0,
    avgAmount: 1680,
    description: '最近购买时间近、消费金额大，但购买频率不高'
  },
  {
    id: 4,
    name: '重要挽留客户',
    level: '中价值',
    type: 'warning',
    userCount: 9500,
    percentage: 20.8,
    avgAmount: 1450,
    description: '购买频率高、消费金额大，但最近购买时间很远'
  },
  {
    id: 5,
    name: '一般价值客户',
    level: '低价值',
    type: 'info',
    userCount: 5800,
    percentage: 12.7,
    avgAmount: 680,
    description: '各项指标都处于中等水平的用户'
  },
  {
    id: 6,
    name: '流失客户',
    level: '低价值',
    type: 'danger',
    userCount: 2728,
    percentage: 6.0,
    avgAmount: 320,
    description: '很久没有购买，购买频率和金额都很低'
  }
  ]
})

// 表格数据（基于API数据）
const tableData = ref([])

// 模拟表格数据（后备数据）
const mockTableData = [
  {
    userId: 'U001',
    userName: '张三',
    totalAmount: 15680,
    orderCount: 28,
    avgOrderAmount: 560,
    lastOrderDate: '2024-01-10',
    favoriteCategory: '电子产品',
    rfmSegment: '重要价值客户'
  },
  {
    userId: 'U002',
    userName: '李四',
    totalAmount: 8900,
    orderCount: 15,
    avgOrderAmount: 593,
    lastOrderDate: '2024-01-08',
    favoriteCategory: '服装鞋帽',
    rfmSegment: '重要发展客户'
  },
  {
    userId: 'U003',
    userName: '王五',
    totalAmount: 12450,
    orderCount: 22,
    avgOrderAmount: 566,
    lastOrderDate: '2023-12-15',
    favoriteCategory: '家居用品',
    rfmSegment: '重要保持客户'
  },
  {
    userId: 'U004',
    userName: '赵六',
    totalAmount: 3200,
    orderCount: 8,
    avgOrderAmount: 400,
    lastOrderDate: '2024-01-12',
    favoriteCategory: '图书音像',
    rfmSegment: '一般价值客户'
  },
  {
    userId: 'U005',
    userName: '钱七',
    totalAmount: 1850,
    orderCount: 5,
    avgOrderAmount: 370,
    lastOrderDate: '2023-11-20',
    favoriteCategory: '运动户外',
    rfmSegment: '流失客户'
  }
]

// 计算属性
const amountDistributionOption = computed(() => {
  return {
    tooltip: {
      trigger: 'axis',
      formatter: '{b}: {c} 人'
    },
    xAxis: {
      type: 'category',
      data: amountDistributionData.value.map(item => item.name),
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      type: 'bar',
      data: amountDistributionData.value.map(item => item.value),
      itemStyle: {
        color: {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [
            { offset: 0, color: '#409EFF' },
            { offset: 1, color: '#79bbff' }
          ]
        }
      }
    }]
  }
})

const frequencyDistributionOption = computed(() => {
  return {
    tooltip: {
      trigger: 'axis',
      formatter: '{b}: {c} 人'
    },
    xAxis: {
      type: 'category',
      data: frequencyDistributionData.value.map(item => item.name)
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      type: 'bar',
      data: frequencyDistributionData.value.map(item => item.value),
      itemStyle: {
        color: {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [
            { offset: 0, color: '#67C23A' },
            { offset: 1, color: '#95d475' }
          ]
        }
      }
    }]
  }
})

const categoryPreferenceOption = computed(() => {
  const data = categoryPreferenceData.value[categoryMetric.value]

  return {
    tooltip: {
      trigger: 'axis',
      formatter: categoryMetric.value === 'sales' ? '{b}: {c} 件' : '{b}: ¥{c}'
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.name),
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      type: 'bar',
      data: data.map(item => item.value),
      itemStyle: {
        color: {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [
            { offset: 0, color: '#E6A23C' },
            { offset: 1, color: '#eebe77' }
          ]
        }
      }
    }]
  }
})

const consumptionTrendOption = computed(() => {
  return {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['消费金额', '订单数量']
    },
    xAxis: {
      type: 'category',
      data: consumptionTrendData.value.dates
    },
    yAxis: [
      {
        type: 'value',
        name: '金额(元)',
        position: 'left'
      },
      {
        type: 'value',
        name: '订单数',
        position: 'right'
      }
    ],
    series: [
      {
        name: '消费金额',
        type: 'line',
        yAxisIndex: 0,
        data: consumptionTrendData.value.amount,
        smooth: true,
        itemStyle: { color: '#F56C6C' }
      },
      {
        name: '订单数量',
        type: 'line',
        yAxisIndex: 1,
        data: consumptionTrendData.value.orders,
        smooth: true,
        itemStyle: { color: '#409EFF' }
      }
    ]
  }
})

const filteredTableData = computed(() => {
  let data = tableData.value.length > 0 ? [...tableData.value] : [...mockTableData]

  if (segmentFilter.value) {
    const filterMap = {
      high: ['重要价值客户', '重要保持客户'],
      medium: ['重要发展客户', '重要挽留客户'],
      low: ['一般价值客户', '流失客户']
    }
    data = data.filter(item => filterMap[segmentFilter.value].includes(item.rfmSegment))
  }

  if (searchKeyword.value) {
    data = data.filter(item =>
      item.userName.includes(searchKeyword.value) ||
      item.userId.includes(searchKeyword.value)
    )
  }

  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value

  return data.slice(start, end)
})

// 方法
const refreshData = async () => {
  await loadConsumptionData()
  await loadTableData()
}

const exportReport = () => {
  ElMessage.success('报告导出功能开发中...')
}

const handleAmountChartClick = (params) => {
  ElMessage.info(`点击了消费金额段: ${params.name}，用户数: ${params.value}`)
}

const handleFrequencyChartClick = (params) => {
  ElMessage.info(`点击了消费频次: ${params.name}，用户数: ${params.value}`)
}

const handleCategoryChartClick = (params) => {
  ElMessage.info(`点击了商品类别: ${params.name}`)
}

const handleTrendChartClick = (params) => {
  ElMessage.info(`点击了趋势数据: ${params.seriesName} - ${params.name}`)
}

const viewUserDetail = (row) => {
  ElMessage.info(`查看用户 ${row.userName} 的详细信息`)
}

const getRfmTagType = (segment) => {
  if (segment.includes('重要价值') || segment.includes('重要保持')) {
    return 'success'
  } else if (segment.includes('重要发展') || segment.includes('重要挽留')) {
    return 'warning'
  } else if (segment.includes('一般价值')) {
    return 'info'
  } else {
    return 'danger'
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 加载消费画像分析数据
const loadConsumptionData = async () => {
  try {
    loading.value = true
    const response = await getConsumptionProfileAnalysis()

    if (response.success) {
      apiData.value = response.data

      // 更新平均频次
      if (response.data.summary.avg_frequency) {
        avgFrequency.value = response.data.summary.avg_frequency
      }

      ElMessage.success('数据加载成功')
    } else {
      ElMessage.error(response.message || '获取消费分析数据失败')
      // 使用模拟数据作为后备
      loadMockData()
    }
  } catch (error) {
    console.error('获取消费分析数据失败:', error)
    ElMessage.error('获取消费分析数据失败，使用模拟数据')
    // 使用模拟数据作为后备
    loadMockData()
  } finally {
    loading.value = false
  }
}

// 加载表格数据
const loadTableData = async () => {
  try {
    tableLoading.value = true
    const params = {
      page: currentPage.value,
      page_size: pageSize.value,
      search: searchKeyword.value,
      segment: segmentFilter.value
    }

    const response = await getConsumptionTableData(params)

    if (response.success) {
      tableData.value = response.data.table_data
      totalRecords.value = response.data.pagination.total_records
    } else {
      // 使用模拟数据
      tableData.value = mockTableData
      totalRecords.value = mockTableData.length
    }
  } catch (error) {
    console.error('获取表格数据失败:', error)
    // 使用模拟数据
    tableData.value = mockTableData
    totalRecords.value = mockTableData.length
  } finally {
    tableLoading.value = false
  }
}

// 加载模拟数据
const loadMockData = () => {
  // 这里可以设置一些模拟数据，如果需要的话
}

// 生命周期
onMounted(() => {
  loadConsumptionData()
  loadTableData()
})
</script>

<style scoped>
.consumption-profile {
  padding: 0;
  background-color: transparent;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 24px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.header-content h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.header-content p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

/* 消费指标 */
.consumption-metrics {
  margin-bottom: 24px;
}

.metric-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  cursor: pointer;
  overflow: hidden;
  position: relative;
}

.metric-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #409EFF, #67C23A);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.metric-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.metric-card:hover::before {
  opacity: 1;
}

.metric-content {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
}

.metric-icon {
  padding: 12px;
  border-radius: 12px;
  background: rgba(64, 158, 255, 0.1);
}

.metric-info h3 {
  margin: 0 0 8px 0;
  color: #666;
  font-size: 14px;
  font-weight: 500;
}

.metric-value {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
  font-weight: 700;
  line-height: 1;
}

.metric-change {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  font-weight: 500;
}

.metric-change.up {
  color: #67C23A;
}

.metric-change.down {
  color: #F56C6C;
}

/* 图表区域 */
.consumption-charts {
  margin-bottom: 24px;
}

.chart-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.chart-total {
  color: #666;
  font-size: 14px;
  background: #f0f0f0;
  padding: 4px 8px;
  border-radius: 4px;
}

.chart-container {
  height: 300px;
  padding: 20px 0;
}

/* RFM分析 */
.rfm-analysis {
  margin-bottom: 24px;
}

.rfm-analysis .el-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.rfm-legend {
  display: flex;
  gap: 16px;
  align-items: center;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #666;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 2px;
}

.rfm-content {
  padding: 20px 0;
}

.rfm-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.rfm-item {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.rfm-item:hover {
  background: #e9ecef;
  transform: translateY(-2px);
}

.rfm-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.rfm-header h4 {
  margin: 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.rfm-metrics {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}

.rfm-metric {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.metric-label {
  font-size: 12px;
  color: #666;
}

.rfm-metric .metric-value {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.rfm-description {
  font-size: 12px;
  color: #999;
  line-height: 1.4;
}

/* 表格 */
.consumption-table {
  width: 100%;
}

.consumption-table .el-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  width: 100%;
}

.consumption-table .el-table {
  width: 100% !important;
}

.consumption-table .el-card :deep(.el-card__body) {
  padding: 20px;
  width: 100%;
  overflow-x: auto;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.table-controls {
  display: flex;
  gap: 12px;
  align-items: center;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .consumption-metrics .el-col {
    margin-bottom: 16px;
  }

  .consumption-charts .el-col {
    margin-bottom: 20px;
  }

  .rfm-grid {
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }

  .header-actions {
    justify-content: center;
    flex-wrap: wrap;
  }

  .metric-content {
    flex-direction: column;
    text-align: center;
    gap: 12px;
  }

  .chart-header {
    flex-direction: column;
    gap: 12px;
    text-align: center;
  }

  .rfm-legend {
    flex-direction: column;
    gap: 8px;
  }

  .table-header {
    flex-direction: column;
    gap: 12px;
  }

  .table-controls {
    justify-content: center;
    flex-wrap: wrap;
  }

  .rfm-grid {
    grid-template-columns: 1fr;
  }

  .rfm-metrics {
    flex-direction: column;
    gap: 12px;
  }

  .rfm-metric {
    flex-direction: row;
    justify-content: space-between;
  }

  .chart-container {
    height: 250px;
  }
}

@media (max-width: 480px) {
  .consumption-profile {
    padding: 0 16px;
  }

  .page-header {
    padding: 16px;
  }

  .metric-content {
    padding: 16px;
  }

  .metric-value {
    font-size: 20px;
  }

  .chart-container {
    height: 200px;
    padding: 10px 0;
  }

  .header-actions {
    flex-direction: column;
    width: 100%;
  }

  .header-actions .el-select,
  .header-actions .el-button {
    width: 100%;
  }

  .rfm-item {
    padding: 16px;
  }

  .rfm-header {
    flex-direction: column;
    gap: 8px;
    text-align: center;
  }
}

/* 超小屏幕适配 */
@media (max-width: 360px) {
  .metric-content {
    padding: 12px;
  }

  .chart-container {
    height: 180px;
  }

  .table-controls {
    flex-direction: column;
    width: 100%;
  }

  .table-controls .el-input,
  .table-controls .el-select {
    width: 100% !important;
    margin-bottom: 8px;
  }

  .rfm-item {
    padding: 12px;
  }

  .rfm-metrics {
    gap: 8px;
  }
}
</style>
